(function() {
    'use strict';
    angular.module('BlurAdmin.theme')
        .factory('TokenInterceptor', function($q, $window, $location, $rootScope) {
            return {
                request: function(config) {
                    if (config.url.indexOf("up.qiniu.com") == -1) {
                        config.headers = config.headers || {};
                        if (localStorage.getItem('user_inof')) { //$window.sessionStorage.token
                            var user = JSON.parse(localStorage.getItem('user_inof'));
                            config.headers.Authorization = 'Bearer ' + user.access_token; //$window.sessionStorage.token;
                            config.headers.sssss = 'Bearer ' + user.access_token; //$window.sessionStorage.token;

                        }
                    }

                    return config;
                },

                requestError: function(rejection) {
                    return $q.reject(rejection);
                },

                /* Set Authentication.isLogged to true if 200 received */
                response: function(response) {
                    if (response != null && response.status == 200 && localStorage.getItem('token') && !$rootScope.isLogged) {
                        $rootScope.isLogged = true;
                    }
                    return response || $q.when(response);
                },

                /* Revoke client authentication if 401 is received */
                responseError: function(rejection) {
                    if (rejection != null && rejection.status === 401 && (localStorage.getItem('token') || $rootScope.isLogged)) {
                        location.href = go_url;
                    }
                    return $q.reject(rejection);
                }
            };
        })
})();